//
//  GenericConvenientPayHomeController.m
//  HuLaQuan
//
//  Created by hok on 1/21/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "GenericConvenientPayHomeController.h"

#import "ConvenientPayInputInfoCell.h"
#import "ConfirmButtonCell.h"

#import "ConvenientPayFinishInfoController.h"

//Logic Model
#import "GetUserAccountInfoEngine.h"
#import "ConvenientPayOrderEngine.h"

#import "PayCompanyChooseController.h"

//Jump back
#import "BalanceHomeViewController.h"
@interface GenericConvenientPayHomeController ()<UITextFieldDelegate>

@property (nonatomic,strong) GetUserAccountInfoEngine *getUserAccountInfoEngine;

@property (nonatomic,strong) ConvenientPayOrderEngine *convenientPayOrderEngine;

@property (nonatomic,strong) NSString *orderPrintedID;


/**
 *  Company List
 */
@property (nonatomic,strong) NSArray *companyList;

@property (nonatomic, copy) NSString *listFileName;

@end

static NSString * const ConvenientPayInputInfoCellIdentifier = @"ConvenientPayInputInfoCell";
static NSString * const ConfirmButtonCellIdentifier = @"ConfirmButtonCell";

@implementation GenericConvenientPayHomeController
/**
 *  获取用户银行卡信息的逻辑模型
 *
 *
 */
- (GetUserAccountInfoEngine *)getUserAccountInfoEngine
{
    if (!_getUserAccountInfoEngine) {
        _getUserAccountInfoEngine = [[GetUserAccountInfoEngine alloc] init];
    }
    return _getUserAccountInfoEngine;
}

- (ConvenientPayOrderEngine *)convenientPayOrderEngine
{
    if (!_convenientPayOrderEngine) {
        _convenientPayOrderEngine = [[ConvenientPayOrderEngine alloc] init];
    }
    return _convenientPayOrderEngine;
}
- (void)setPayType:(CPPayType)payType
{
    _payType = payType;
    switch (_payType) {
        case PayElec:
            self.listFileName = @"ElectricityCompanies";
            break;
        case PayGas:
            self.listFileName = @"GasCompanies";
            break;
        case PayWater:
            self.listFileName = @"WaterCompanies";
            break;
        case PayTrafic:
            self.listFileName = @"TraficFineCompanies";
            break;
        default:
            break;
    }
}
- (NSArray *)companyList
{
    if (!_companyList) {
        
        _companyList= [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:self.listFileName ofType:@"plist"]];
        
    }
    return _companyList;
}
- (NSMutableDictionary *)companyInfo
{
    if (!_companyInfo) {
        _companyInfo = [[NSMutableDictionary alloc] init];
    }
    return _companyInfo;
}

- (NSArray *)items{
    if (!_items) {
        _items = [[NSArray alloc] init];
    }
    return _items;
}

- (void)setupUI
{
    [self setupNavBackButton];
    
    [self setupFooterForTableView];
    
    [self.tableView registerNib:[ConvenientPayInputInfoCell nib] forCellReuseIdentifier:ConvenientPayInputInfoCellIdentifier];
    [self.tableView registerNib:[ConfirmButtonCell nib] forCellReuseIdentifier:ConfirmButtonCellIdentifier];
    
    
    self.items = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ElectricityPayItem" ofType:@"plist"]];
    
    [self createNavigationBarRightBarButtonItemWithTitle:@"贵阳"];
    

    [self setupChildControllerUI];
}

- (void)rightAction
{
    
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"ConvenientPay" bundle:nil];
    [self.navigationController pushViewController:[storyBoard instantiateViewControllerWithIdentifier:@"PlistChooseController"] animated:YES];
}

- (void)setupChildControllerUI
{
    
}
#pragma mark - Button Events 下一步按钮
- (void)tapNextButton
{
    if(self.orderPrintedID.length)
    {
        
        /**
         *  获取订单信息，暂时公司号是固定的
         */
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        
        
        if (self.payType == PayPhone) {
            [self.convenientPayOrderEngine getPhoneOrderInfoWithID:self.orderPrintedID andType:[self getTypeCodeFromCPType] andCompany:@"443701060120050" andValue:@"0.01"];
        }else{
            [self.convenientPayOrderEngine getOrderInfoWithID:self.orderPrintedID andType:[self getTypeCodeFromCPType] andCompany:@"443701060120050"];
        }
    }else{
        [self.view makeToast:@"您还未输入付款单号"];
    }
    
    
    
    
}
#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserAccountInfoFinish:) name:@"GetUserAccountInfoFinish" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCPOrderInfoFinish:) name:@"GetCPOrderInfoFinish" object:nil];

    if(self.isFromAddCardFinish)
    {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.getUserAccountInfoEngine getAccoutInfo];
    }
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetUserAccountInfoFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetCPOrderInfoFinish" object:nil];
}


    
#pragma mark - Call back

- (void)getCPOrderInfoFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        
        self.orderInfo = messageDic[@"result"];
        
        NSLog(@"%@",self.orderInfo);
        
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.getUserAccountInfoEngine getAccoutInfo];
        
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}




- (void)getUserAccountInfoFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        
        if (!messageDic[@"result"][@"cardList"] ) {
            
            UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"您还未绑定银行卡，无法消费，请立即绑定银行卡" andBlock:^(UIAlertAction *action ) {
                ////NSLog(@"%@",action.title);
                if ([action.title isEqualToString:@"好的"]) {
                    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"BankCard" bundle:nil];
                    if ([messageDic[@"result"][@"initPay" ] isEqualToString:@"true"]) {
                        
                        //初次设置支付密码
                        [self.navigationController pushViewController:[storyBoard instantiateViewControllerWithIdentifier:@"AddCardFirstInputPasswordController"] animated:YES];
                        
                    }else{
                        [self.navigationController pushViewController:[storyBoard instantiateViewControllerWithIdentifier:@"AddCardCheckPasswordViewController"] animated:YES];
                        
                    }
                }else{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
                
            } type:@"confirmAndCancel"];
            [self presentViewController:x animated:YES completion:nil];
            
            
        }else{
            
            NSLog(@"%@",messageDic[@"result"][@"cardList"] );
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"ConvenientPay" bundle:nil];
            
            ConvenientPayFinishInfoController *controller =(ConvenientPayFinishInfoController *) [storyBoard instantiateViewControllerWithIdentifier:@"ConvenientPayFinishInfoController"];
            controller.cardList = messageDic[@"result"][@"cardList"];
            controller.orderInfo = self.orderInfo;
            if (self.companyInfo && self.companyInfo[@"title"]) {
                controller.companyName = self.companyInfo[@"title"];
            }else{
                controller.companyName = [self.companyList firstObject];
            }
            controller.navigationItem.title = self.title;
            [self.navigationController pushViewController:controller animated:YES];
        }
        
        
        
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}

/**
 *  子类中复写
 */
- (void)getOrderFinish
{
    
}
#pragma mark UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return indexPath.row ==2 ? kConfirmButtonCellHeight : kNormalCellHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 8;
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row < 2) {
        ConvenientPayInputInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:ConvenientPayInputInfoCellIdentifier
                                                               forIndexPath:indexPath];
        cell.textField.placeholder = self.items[indexPath.row][@"placeholder"];
        
        cell.textField.delegate = self;
        
        [cell.textField addTarget:self action:@selector(payFieldWithText:) forControlEvents:UIControlEventEditingChanged];
        cell.textField.tag = indexPath.row;
        
        if (indexPath.row == 0) {
            cell.textField.enabled = NO;
            if(self.companyInfo && self.companyInfo[@"title"])
            {
                cell.textField.text = self.companyInfo[@"title"];
            }else{
                cell.textField.text = [self.companyList firstObject];
            }
            
        }else{
            cell.arrow.hidden = YES;
            cell.titleLabel.text = self.items[indexPath.row][@"title"];
        }
        
        return cell;
        
    }else{
        ConfirmButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:ConfirmButtonCellIdentifier
                                                                  forIndexPath:indexPath];
        
        [cell.confirmButton setTitle:@"下一步" forState:UIControlStateNormal];
        cell.confirm = (ClickBlock)^(){
            [self tapNextButton];
        };
        
        return cell;
    }
    
    
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.row) {
        
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"ConvenientPay" bundle:nil];
        PayCompanyChooseController *companylist =(PayCompanyChooseController *)[storyBoard instantiateViewControllerWithIdentifier:@"PayCompanyChooseController"];
        companylist.type = self.payType;
        [self.navigationController pushViewController:companylist animated:YES];
    }
    
}

#pragma mark - Text Field Value
//getInformation
- (void)payFieldWithText:(UITextField *)textField
{
    switch (textField.tag) {
        case 1:
            self.orderPrintedID = textField.text;
            break;
        default:
            self.orderPrintedID = textField.text;
            break;
    }
}
#pragma mark - Function

/**
 *  通过Controller 的type转换成不同type的报文
 *
 *  @return <#return value description#>
 */
- (NSString *)getTypeCodeFromCPType
{
    switch (self.payType) {
        case PayElec:
            return @"gzEle";
            break;
        case PayWater:
            return @"gzWater";
            break;
        case PayGas:
            return @"gzGas";
            break;
        case PayTrafic:
            return @"gzTraFine";
            break;
        case PayPhone:
            return @"gzTel";
            break;
        default:
            break;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

- (void)goBackAction
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    
    UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"是否放弃缴费" andBlock:^(UIAlertAction *action ) {
        if ([action.title isEqualToString:@"好的"]) {
            if ([self.navigationController.viewControllers[0] isKindOfClass:[BalanceHomeViewController class]])
            {
                [self.navigationController popToViewController:self.navigationController.viewControllers[0] animated:YES];
                
            }
            
        }
        
    }  type:@"confirmAndCancel"];
    [self presentViewController:x animated:YES completion:nil];
}

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    
    
//    
//    if (<#condition#>) {
//        <#statements#>
//    }
}




@end
